---
title: ''
output: pdf_document
geometry: "top=1in, bottom=1in, left=1in, right=1in"
header-includes:
- \usepackage{caption}
- \usepackage{lscape}
---

\newcommand{\blandscape}{\begin{landscape}}
\newcommand{\elandscape}{\end{landscape}}

\captionsetup[table]{labelformat=empty}


```{r setup, include=FALSE, message=FALSE}

# Package setup
if (!require("pacman")) install.packages("pacman", repos = "http://cran.us.r-project.org"); library(pacman);
pacman::p_load(yaml, readr, tidyr, argparse, stringr, here, glue, dplyr, knitr, kableExtra, forcats);

# Working directory and command line argument setup
task_output = "realized_risk_table"
current_script = paste0("generate_tables_and_figures/gen_", task_output, "/src/gen_", task_output, ".Rmd")
here::i_am(current_script)
source(here("R", "project_functions.R"))
task_dir = here(dirname(dirname(file.path(current_script))))
knitr::opts_knit$set(root.dir = task_dir)
cl_args <- parse_make_args(c(
  "RMD_FILE",
  "REALIZED_RISK_BY_PATHWAY",
  "BASELINE_RISK_BY_PATHWAY",
  "OUTCOME_LABELS_FILE",
  "CONFIG_FILE",
  "OUT_DIR"
), inter_active = TRUE, task_dir = task_dir)

knitr_setup()
options(knitr.kable.NA = '')
```

```{r}

config <- read_yaml(cl_args$CONFIG_FILE)

ylabels <- read_csv(cl_args$OUTCOME_LABELS_FILE) %>% 
  rename(outcome = value)

source('../R/table_functions.R')
table_config <- read_yaml('../hand/tables_config.yaml')

```

```{r}

# Prepare baseline section
baseline_pathway_raw <- read_csv(cl_args$BASELINE_RISK_BY_PATHWAY, show_col_types = F) 

baseline_pathway <- baseline_pathway_raw%>%
  filter(outcome %in% config$baseline_rows) %>%
  mutate(outcome = fct_relevel(outcome, config$baseline_rows)) %>%
  arrange(outcome) %>%
  mutate(outcome_order = row_number()) %>%
  mutate(outcome = gsub("_pre", "", outcome)) %>%
  left_join(ylabels, by = "outcome")
  
```

```{r}
# Prepare realized risk

real_risk_pathway_raw <- read_csv(cl_args$REALIZED_RISK_BY_PATHWAY, show_col_types = F)

real_risk_pathway <- real_risk_pathway_raw %>%
  filter(outcome %in% config$realized_risk_rows) %>%
  mutate(outcome = fct_relevel(outcome, config$realized_risk_rows)) %>%
  arrange(outcome) %>%
  mutate(outcome_order = row_number()) %>%
  mutate(outcome = gsub("_post_\\d{2}", "", outcome)) %>%
  left_join(ylabels, by = "outcome")
  
```

\blandscape

```{r}

# Filter to window and outcomes
outcomes_table <- bind_rows(baseline_pathway,
                            real_risk_pathway) %>%
  mutate(across(.cols = where(is.numeric),
                .fns = ~ case_when(is.na(.x) ~ NA_character_,
                                   label == 'N' ~ as.character(.x),
                                   .x > .99 ~ fmt(.x, table_config$digits$sum_stats_greater_than_1),
                                   TRUE ~ fmt(.x, table_config$digits$sum_stats_less_than_1))),
         pval = case_when(pval < .001 ~ "<.001",
                          is.na(pval) ~ NA_character_,
                          TRUE ~ as.character(pval)),
         across(.cols = where(is.numeric),
                .fns = ~case_when(is.na(.x) ~ NA_character_,
                                  TRUE ~ as.character(.x))))

n_baseline_rows <- outcomes_table %>% filter(type == "baseline") %>% nrow()
n_realized_rows <- outcomes_table %>% filter(type == "realized") %>% nrow()

# Make table
table <- outcomes_table %>%
  mutate(label = case_when(label == "Risk Score" & type == "baseline" ~ "Predicted Involvement in a Violent Gun Crime",
                           label == "Involvement in a Violent Gun Crime" & type == "realized" ~ "Involved in a Violent Gun Crime",
                           label == "Ever Shot" & type == "realized" ~ "Ever Shot or Killed",
                           TRUE ~ label)) %>%
  select(all_of(names(config$columns))) %>%
  kable(booktabs = table_config$booktabs, 
        longtable = table_config$longtable,
        col.names = unlist(config$columns),
        align = c(table_config$alignment$text,
                  rep(table_config$alignment$numeric,
                      length(config$columns) - 1)),
        linesep = "") %>%
  kable_styling(font_size = table_config$font_size) %>%
  group_rows("Baseline", 1, n_baseline_rows) %>%
  group_rows("Realized Risk Among Controls", 
            n_baseline_rows + 1,
             n_baseline_rows + n_realized_rows) %>%
  column_spec(1, width = config$col_width$text) %>%
  column_spec(2:5, width = config$col_width$numeric, latex_valign = "m") %>%
  column_spec(6, width = "10em", latex_valign = "m")

table

# SAVE

timestamp <- get_timestamp()
task_output <- "realized_risk" # To match what is on overleaf already
writeLines(table, paste0(cl_args$OUT_DIR, "/", task_output, "_up_to_date.tex"))
writeLines(table, paste0(cl_args$OUT_DIR, "/", task_output, "_", timestamp, ".tex"))

```

\elandscape